import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder, ValidatorFn } from '@angular/forms';
import { OptionItem, MessageService } from '@iux/live';

@Component({
  templateUrl: './demo8.component.html',
})
export class Demo8Component implements OnInit {
  constructor(private fb: FormBuilder, private message: MessageService) {}
  data: OptionItem[];
  formGroup: FormGroup;
  loading = false;

  ngOnInit() {
    this.data = this.initData();
    this.initForm();
  }
  initData() {
    return [
      {
        label: 'email',
        isLeaf: true,
      },
      {
        label: 'phone',
        isLeaf: true,
      },
    ];
  }
  initForm() {
    this.formGroup = this.fb.group({
      name: ['Jack', [Validators.required, this.validName()]],
      password: ['', Validators.required],
      contact: ['', Validators.required],
    });
    this.onContactChange('email');
  }

  // 自定义校验
  validName(): ValidatorFn {
    return (control: FormControl): { [key: string]: any } => control.value !== 'abcd' ? null : { nameExist: true };
  }

  reset() {
    this.formGroup.reset({
      name: 'Jack',
      password: '',
      contact: '',
    });
    this.onContactChange('email');
  }

  register() {
    for (const i of Object.keys(this.formGroup.controls)) {
      this.formGroup.controls[i].markAsDirty();
      this.formGroup.controls[i].updateValueAndValidity();
    }
    // 判断校验，完成校验进行下一步操作
    if (!this.formGroup.invalid) {
      this.message.success('Next...');
    }
  }

  onContactChange(value) {
    const ctrl = new FormControl('', [Validators.maxLength(10)]);
    if (value === 'email') {
      this.formGroup.addControl('email', ctrl);
      this.formGroup.removeControl('phone');
    } else if (value === 'phone') {
      this.formGroup.addControl('phone', ctrl);
      this.formGroup.removeControl('email');
    }
  }
}
